<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>layui</title>
    <meta name="renderer" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <link rel="stylesheet" href="/static/admin/lib/layui-v2.5.5/css/layui.css" media="all">
    <link rel="stylesheet" href="/static/admin/css/public.css" media="all">
    <style>
        #cisLoading {
            position: fixed;
            left: 50%;
            top: 50%;
            z-index: 1000;
            display: none;
        }
    </style>
</head>
<body>
<div class="layuimini-container">
    <div class="layuimini-main">

        <script type="text/html" id="toolbarDemo">
            <div class="layui-btn-container">
                <button class="layui-btn layui-btn-normal layui-btn-sm data-add-btn" lay-event="add"> 添加 </button>
                <button class="layui-btn layui-btn-sm layui-btn-danger data-delete-btn" lay-event="delete"> 删除 </button>
            </div>
        </script>

        <table class="layui-hide" id="roleTableId" lay-filter="currentTableFilter"></table>

        <script type="text/html" id="currentTableBar">
            <a class="layui-btn layui-btn-normal layui-btn-xs data-count-edit" lay-event="edit">赋予菜单</a>
        </script>

    </div>
</div>

<script type="text/html" id="MenuSelectTool">

    <select name="role" lay-verify="required">

    </select>

</script>
<!-- 菜单树形 -->

<div id="menuTree" style="display: none">
    <form class="layui-form">
        <div id="menuTreeDiv"></div>

        <div class="layui-form-item">
            <div class="layui-input-block">
                <button class="layui-btn" lay-submit lay-filter="menuTreeSubmit">立即提交</button>
                <button type="reset" class="layui-btn layui-btn-primary">重置</button>
            </div>
        </div>
    </form>


</div>
<!-- 加载 -->
<div id="cisLoading">
    <img src="/static/admin/images/loading.jpg" style="width:200px;height:200px" />
</div>
<script src="/static/admin/lib/layui-v2.5.5/layui.js" charset="utf-8"></script>
<script>
    layui.use(['form', 'table','jquery','tree'], function () {
        var $ = layui.jquery,
            form = layui.form,
            table = layui.table;
        var tree = layui.tree;

        table.render({
            elem: '#roleTableId',
            url: '/admin/queryRolePage',
            toolbar: '#toolbarDemo',
            defaultToolbar: [],
            cols: [
                [
                {type: "checkbox"},
                {field: 'roleId', title: 'ID'},
                {field: 'roleName', title: '角色名称'},
                {field: 'roleDetails', title: '角色描述'},
                {field:'roleLevel',title:'角色等级(越小等级越高)'},
                {title:'角色所属菜单',templet:function (res) {

                        return queryMenuByRoleId(res.roleId);

                    }},
                {title: '操作', minWidth: 150, toolbar: '#currentTableBar', align: "center"}
                ]
            ],
            page: true,
            done: function (res, curr, count) {
                //由于layui 设置了超出隐藏，所以这里改变下，以兼容操作按钮的下拉菜单
                $(".layui-table-body, .layui-table-box, .layui-table-cell").css('overflow', 'visible');
                // 一定要重新渲染表单
                form.render();
            }
        });

        // 监听搜索操作
        form.on('submit(data-search-btn)', function (data) {
            var result = JSON.stringify(data.field);
            layer.alert(result, {
                title: '最终的搜索信息'
            });

            //执行搜索重载
            table.reload('roleTableId', {
                page: {
                    curr: 1
                }
                , where: {
                    searchParams: result
                }
            }, 'data');

            return false;
        });

        /**
         * toolbar监听事件
         */
        table.on('toolbar(currentTableFilter)', function (obj) {
            if (obj.event === 'add') {  // 监听添加操作

                layer.msg("正在很努力开发呢！")

            } else if (obj.event === 'delete') {  // 监听删除操作
                layer.msg("正在很努力开发呢！")
            }
        });

        //监听表格复选框选择
        table.on('checkbox(currentTableFilter)', function (obj) {
            console.log(obj)
        });

        //全局roleId
        var roleId = 0;
        table.on('tool(currentTableFilter)', function (obj) {
            var data = obj.data;
            roleId = data.roleId;

            if (obj.event === 'edit') {


                var index = layer.open({
                    title: '赋予菜单',
                    type: 1,
                    area:['500px','400px'],
                    content: $('#menuTree'),
                    success:function () {
                        var count = 0;

                        $.ajax({
                            url:'/admin/queryMenuTree/'+data.roleId,
                            type:'post',
                            dataType:'json',
                            async: true,
                            beforeSend:function(XMLHttpRequest){
                                // 过滤某种条件下才控制loading效果
                                $("#cisLoading").show();

                            },
                            success:function (res) {

                                $("#cisLoading").hide();
                                if (res.code == 200){

                                    //渲染树形
                                    var inst1 = tree.render({
                                        elem: '#menuTreeDiv'  //绑定元素
                                        ,id:'menuTreeId'
                                        , showCheckbox: true
                                        , showLine:true
                                        ,data: res.data
                                        ,oncheck: function(obj){

                                            //删除角色菜单关联表
                                            if (!obj.checked){

                                               menuRole("/admin/deleteRoleMenu/"+data.roleId,obj.data.id,obj.data.parent_id);
                                            }


                                        }

                                    });
                                } else {

                                    layer.msg(res.message)

                                }



                            }
                        })

                    }
                });

                return false;
            } else if (obj.event === 'delete') {
                layer.confirm('真的删除行么', function (index) {
                    obj.del();
                    layer.close(index);
                });
            }
        });

        form.on('submit(menuTreeSubmit)', function(data){

            //获得选中的节点
            var checkData = tree.getChecked('menuTreeId');
            var list = new Array();

            list = getChecked_list(checkData);

            $.ajax({
                url:'/admin/addRoleMenu/'+roleId,
                type:'post',
                data:{
                    menuId:list
                },
                dataType:'json',
                async:false,
                success:function (res) {

                    layer.msg(res.message)

                }
            })

            return false; //阻止表单跳转。如果需要表单跳转，去掉这段即可。
        });

        // 获取选中节点的id
        function getChecked_list(data) {
            var id = "";
            $.each(data, function (index, item) {
                if (id != "") {
                    id = id + "," + item.id;
                }
                else {
                    id = item.id;
                }
                var i = getChecked_list(item.children);
                if (i != "") {
                    id = id + "," + i;
                }
            });
            return id;
        }

        //根据角色id获取菜单
        function queryMenuByRoleId(roleId) {
            var html = "";
            $.ajax({
                url:'/admin/queryMenuByRoleId/'+roleId,
                type:'post',
                dataType:'json',
                async:false,
                success:function (res) {

                    html = '<select name="role" lay-verify="required">';

                    if (res.code == 200){
                        var data =  res.data
                        $.each(data,function (index,item) {

                            html += '<option value="'+item.menuId+'">'+item.menuName+'</option>';

                        })

                    }

                    html += '</select>';
                }
            })
            return html;
        }
        //角色菜单关联
        function menuRole(url,menuId,menuManagerId) {

            $.ajax({
                url:url,
                type:'post',
                data:{
                    menuId:menuId,
                    menuManagerId:menuManagerId
                },
                dataType:'json',
                success:function (res) {

                    layer.msg(res.message);

                }
            })

        }

    });


</script>

</body>
</html>
